# -*- coding: utf8 -*-
import markdown
from django import template
from django.core.paginator import Paginator
from markdown.extensions.toc import TocExtension, slugify

from app.models import Article, Category, Tag, Comment, Option

__author__ = 'panshengpeng'

register = template.Library()
md = markdown.Markdown(extensions=[
    'markdown.extensions.extra',
    # 'markdown.extensions.codehilite',
    TocExtension(slugify=slugify),
])


@register.simple_tag
def list_article(category_id=None, tag_id=None, page_no=1):
    query = {}
    if category_id:
        query['category'] = category_id
    if tag_id:
        query['tags'] = tag_id

    articles = Article.objects.filter(**query).order_by("-updated_at")
    paginator = Paginator(articles, 10)  # 每页显示数量
    page = paginator.page(page_no)
    return page


@register.simple_tag
def list_category():
    return Category.objects.all()


@register.simple_tag
def list_tag():
    return Tag.objects.all()


@register.simple_tag
def get_article(article_id):
    article = Article.objects.filter(id=article_id).first()
    # 浏览量增加
    article.increase_views()

    vo = {}
    vo.update(article.__dict__)
    vo['content_html'] = md.convert(article.content)
    # vo['toc_html'] = md.toc

    vo['comments'] = Comment.objects.filter(article=article_id, parent=None).all()
    return vo


@register.simple_tag
def list_article_newest_10():
    return Article.objects.all()[:10]


@register.simple_tag
def list_comment(parent_id):
    return Comment.objects.filter(parent=parent_id).all()


@register.simple_tag
def get_about():
    return Option.objects.filter(option_key="OptionAbout").first()
